package com.wtwd.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wtwd.device.constant.Constants;
import com.wtwd.device.dao.RolePermissionMapper;
import com.wtwd.device.dao.SysPermissionMapper;
import com.wtwd.device.model.entity.SysPermission;
import com.wtwd.device.model.entity.SysRole;
import com.wtwd.device.service.PermissionService;
import com.wtwd.device.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mjy
 * @date 2021/08/05
 * @description
 */
@Service
public class PermissionServiceImpl implements PermissionService {


    @Autowired
    private SysPermissionMapper sysPermisssionMapper;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    private List<Integer> ids = new ArrayList<>(100);

    /**
     * 为保证已生成的权限id不变,采用插入或更新的方式处理
     */
    @PostConstruct
    private void create() {
        ClassPathResource resource = new ClassPathResource("permission.json");
        JSONObject jsonData = null;
        if (resource.exists()) {
            try {
                jsonData = (JSONObject) JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, JSONObject.class,
                        // 自动关闭流
                        Feature.AutoCloseSource,
                        // 允许注释
                        Feature.AllowComment,
                        // 允许单引号
                        Feature.AllowSingleQuotes,
                        Feature.OrderedField
                );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(jsonData.toJSONString());
        //清空权限表记录
        //sysPermissionMapper.clear();
        for (int i = 1; i <= jsonData.size(); i++) {
            JSONObject json = jsonData.getJSONObject(i + "");
            createChild(0, json);
        }
        //删除本次修改中不存在的
        sysPermisssionMapper.deleteByNonId(ids);
        //初始化菜单角色
        initRole();
        //超级管理员初始化所有权限
        initRolePermission();
    }

    /**
     * 初始化管理员权限
     */
    private void initRolePermission() {
        //查询管理员角色id
        //批量添加的菜单权限
        ArrayList<Integer> bathAddPermission = new ArrayList<>();
        SysRole sysRole = sysRoleService.getSysRoleByRoleType(Constants.SYS_USER_ROLE_TYPE_ADMIN);
        if (sysRole != null) {
            List<SysPermission> sysPermissions = sysPermisssionMapper.getAllPermission();
            if (sysPermissions != null && sysPermissions.size() > 0) {
                //获取该角色现有所有权限
                List<Integer> perIdList = rolePermissionMapper.getRolePermissionPerIdByRoleId(sysRole.getRoleId());
                for (SysPermission sysPermission : sysPermissions) {
                     //定义需要添加标志
                     boolean flag =true;
                     if (perIdList!=null&&perIdList.size()>0){
                         for (Integer perId : perIdList) {
                             if (sysPermission.getId().equals(perId)){
                                 flag=false;
                                 break;
                             }
                         }
                     }
                     if (flag){
                         bathAddPermission.add(sysPermission.getId());
                     }
                }
            }
            if (bathAddPermission!=null&&bathAddPermission.size()>0){
                rolePermissionMapper.bathAddRolePermission(sysRole.getRoleId(),bathAddPermission);
            }
        }

    }


    /**
     * 以下操作初始化角色，以及默认收集超级管理员权限
     */
    private void initRole() {
        ArrayList<Integer> roleTypeList = new ArrayList<>();
        roleTypeList.add(Constants.SYS_USER_ROLE_TYPE_ADMIN);
        roleTypeList.add(Constants.SYS_USER_ROLE_TYPE_OPERATOR);
        roleTypeList.add(Constants.SYS_USER_ROLE_TYPE_CUSTOMER);
        List<SysRole> sysRoles = sysRoleService.getSysRoleByRoleTypeList(roleTypeList);
        //记录批量添加角色集合
        ArrayList<SysRole> bathAddSysRole = new ArrayList<>();
        for (Integer roleType : roleTypeList) {
            //定义不存在标志
            boolean flag = true;
            if (sysRoles != null && sysRoles.size() > 0) {
                for (SysRole sysRole : sysRoles) {
                    if (sysRole.getRoleType().equals(roleType)) {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag) {
                SysRole sysRole = new SysRole();
                if (roleType == 1) {
                    sysRole.setRoleType(roleType);
                    sysRole.setRoleName("管理员");
                } else if (roleType == 2) {
                    sysRole.setRoleType(roleType);
                    sysRole.setRoleName("运营商");
                } else if (roleType == 3) {
                    sysRole.setRoleType(roleType);
                    sysRole.setRoleName("客户");
                }
                bathAddSysRole.add(sysRole);
            }
        }
        //批量添加角色
        if (bathAddSysRole != null && bathAddSysRole.size() > 0) {
            sysRoleService.bathAddRoleType(bathAddSysRole);
        }
    }

    /**
     * 初始化菜单
     *
     * @param pid
     * @param json
     */
    private void createChild(Integer pid, JSONObject json) {
        json.put("pid", pid);
        Object children = json.get("children");
        if (pid == 0) {
            json.put("menuType", "1");
        } else {
            json.put("menuType", "2");
        }
        sysPermisssionMapper.saveOrUpdate(json);
        ids.add(json.getInteger("id"));
        //插入数据并且返回主键
        if (children instanceof JSONArray) {
            JSONArray array = (JSONArray) children;
            //存在子节点继续遍历
            for (int i = 0; i < array.size(); i++) {
                createChild(json.getInteger("id"), array.getJSONObject(i));
            }
        } else if (children instanceof String) {
            // 插入 按钮类型的权限
            String s = (String) children;
            if ("".equals(s)) return;
            if (s.startsWith("-")) {
                s = "添加,删除,修改" + s.replace("-", "");
            }
            String[] split = s.split(",");
            //默认增删改
            for (String name : split) {
                JSONObject param = new JSONObject();
                param.put("menuType", "10");
                param.put("pid", json.getInteger("id"));
                param.put("name", name);
                sysPermisssionMapper.saveOrUpdate(param);
                ids.add(param.getInteger("id"));
            }
            //批量插入或更新 无法保存正确返回所有主键
//            sysPermissionMapper.savePermissionBatch(params);
        }
    }


}
